package projetstackoverflow

import org.h2.command.ddl.CreateLinkedTable;

class MessageController {

    def index() { }
	
	def upVote(Long id) {
		def instance = Message.get(id)
		if(instance)
		{
			def uri
			if(instance instanceof Question)
				uri = createLink(controller:'question', action:'show', params:['id':id])
			else
				uri = createLink(controller:'question', action:'show', params:['id':instance.question.id])
			uri -=  request.contextPath
			def author = session.author
			if (author)
			{
				if(author.id != instance.author.id)
				{
					def votesAll = instance.votes
					def votes = votesAll.findAll{it.author.id == author.id}
					if(votes == null || votes.size() == 0)
					{
						def newVote = new Vote(author:author, message:instance, value:Vote.UP_VOTE, date:new Date())
						newVote.save()
					}
					else if(votes.size() == 1)
					{
						def vote = votes.first()
						if(vote.value == Vote.DOWN_VOTE)
						{
							vote.value = Vote.NO_VOTE
						}
						else if(vote.value == Vote.NO_VOTE)
						{
							vote.value = Vote.UP_VOTE
						}
						vote.save()
					}
				}
					redirect(uri:uri)
				
			}
			else
			{
				uri = createLink(controller:'message', action:'upVote', params:['id':id])-request.contextPath
				redirect(controller:'author', action:'login', params:['lastUri':uri])
			}
		}
		
	}
	
	def downVote(Long id) {
		
		def instance = Message.get(id)
		if(instance)
		{
			def uri
			if(instance instanceof Question)
				uri = createLink(controller:'question', action:'show', params:['id':id])
			else
				uri = createLink(controller:'question', action:'show', params:['id':instance.question.id])
			uri-=  request.contextPath
			def author = session.author
			if (author)
			{
				if(author.id != instance.author.id)
				{
					def votesAll = instance.votes
					def votes = votesAll.findAll{it.author.id == author.id}
					if(votes == null || votes.size() == 0)
					{
						def newVote = new Vote(author:author, message:instance, value:Vote.DOWN_VOTE, date:new Date())
						newVote.save()
					}
					else if(votes.size() == 1)
					{
						def vote = votes.first()
						if(vote.value == Vote.UP_VOTE)
						{
							vote.value = Vote.NO_VOTE
						}
						else if(vote.value == Vote.NO_VOTE)
						{
							vote.value = Vote.DOWN_VOTE
						}
						vote.save()
					}
				}
				
				redirect(uri:uri)
				
			}
			else
			{
				uri = createLink(controller:'message', action:'downVote', params:['id':id])-request.contextPath
				redirect(controller:'author', action:'login', params:['lastUri':uri])
			}
		}
		
	}
}
